<template>
  <!-- 这是新建假单 -->
  <div>
    <div class="item form_box">
      <h1>请假单</h1>
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="表单id" v-if="pageType==='search'" style="float:left;margin:0 20px;">
          <!-- <el-input v-model="form.id" :readonly="true"></el-input> -->
          <span>{{form.id}}</span>
        </el-form-item>
        <el-form-item label="用户id" style="float:left;margin:0 20px;">
          <!-- <el-input v-model="form.uid" :readonly="true"></el-input> -->
          <span>{{form.uid}}</span>
        </el-form-item>
        <el-form-item label="请假人" style="float:left;margin:0 20px;">
          <!-- <el-input v-model="form.name"></el-input> -->
          <span>{{form.name}}</span>
        </el-form-item>
        <el-form-item label="创建时间" v-if="pageType==='search'" style="float:left;margin:0 20px;">
          <!-- <el-input v-model="form.createTime" :readonly="true"></el-input> -->
          <span>{{form.createTime}}</span>
        </el-form-item>
        <el-form-item label>
          <div></div>
        </el-form-item>
        <el-form-item label="请假时间" prop="datetime">
          <el-date-picker
            format="yyyy-MM-dd HH"
            value-format="yyyy-MM-dd HH"
            v-model="form.datetime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="请假类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="病假"></el-radio>
            <el-radio label="事假"></el-radio>
            <el-radio label="调休"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="请假原因" prop="reason">
          <el-input type="textarea" v-model="form.reason"></el-input>
        </el-form-item>
        <el-form-item v-if="isShowBtns">
          <!-- <el-button type="primary">取消</el-button> -->
          <el-button type="primary" @click="handleCreate('form')">创建</el-button>
        </el-form-item>
        <div style="clear:both;"></div>
      </el-form>
    </div>

    <div class="item" v-if="pageType==='search'">
      <h1 style="display:inline-block;">假单状态</h1>
      <span style="margin-left:10px;">{{fakeState}}</span>
    </div>

    <div class="item">
      <h1>审核流程</h1>
      <el-steps :active="currentStep" align-center>
        <!-- :icon="item.icon" -->
        <el-step
          v-for="item in relativeNetwork"
          :key="item.id"
          :title="item.name"
          :description="item.desc"
        ></el-step>
      </el-steps>
    </div>
  </div>
</template>
<script>
import { create_fakeinfo_one, get_fakeinfo_one } from "@/api/fake";
import { getObjByString, getMap, isArray, getDataBySession } from "@/utils";
import { type } from "os";
import { debug } from "util";
export default {
  props: {
    id: {
      // 表单id
      type: String
    },
    pageType: {
      // create search 页面属性
      type: String
    }
  },
  data() {
    return {
      form: {
        id: 0, // 表单id（不可修改）
        uid: "", // 创建者id（不可修改）
        name: "", // 创建者姓名（不可修改）
        datetime: [], // 请假日期
        type: "", // 请假类型
        reason: "" // 请假原因
      },
      currentStep: 0, // 当前进度步骤
      relativeNetwork: [], // 审核关系网
      UserInfo: {},
      fakeState: "", // 请假单状态
      rules: {
        datetime: [
          {
            required: true,
            message: "请选择请假日期",
            trigger: "change"
          }
        ],
        type: [
          { required: true, message: "请选择请假类型", trigger: "change" }
        ],
        reason: [{ required: true, message: "请填写请假原因", trigger: "blur" }]
      }
    };
  },
  computed: {
    // 是否显示创建按钮
    isShowBtns() {
      return this.pageType == "create";
    }
  },
  watch: {
    id: {
      handler(n, o) {
        this.init();
      }
    },
    pageType: {
      handler(n, o) {
        this.init();
      }
    }
  },
  created() {
    this.init();
  },
  methods: {
    // // 注册公司信息
    // addCompany(param) {
    //   let data = {
    //     companyId: "A",
    //     companyName: "云蟾游戏",
    //     cbUrl: "http://xxx.json"
    //   };
    //   add_company(data, () => {
    //     alert(data.companyName + "注册成功");
    //   });
    // },
    init() {
      this.setUserInfo();
      if (this.pageType == "search") {
        this.getFakeOneinfo();
      }
      if (this.pageType == "create") {
        this.restoreFormData();
      }
    },
    // 设置用户信息
    setUserInfo() {
      this.UserInfo = JSON.parse(getDataBySession("UserInfo"));
      if (this.UserInfo == null) {
        this.$router.push({ path: "/login" });
      }
      this.UserInfo.relationship = JSON.parse(this.UserInfo.relationship);
    },
    // 设置请假单当前状态
    setFakeState() {
      if (this.form.state == 0) this.fakeState = "待审核";
      if (this.form.state == 1) this.fakeState = "审核已通过";
      if (this.form.state == 2) this.fakeState = "审核已拒绝";
    },
    // 清空表单数据
    restoreFormData() {
      for (let k in this.form) {
        this.form[k] = "";
        // console.log(this.form[k]);
      }
      this.form.id = 0;
      this.form.uid = this.UserInfo.uid;
      this.form.name = this.UserInfo.relationship[0]["name"];
      this.form.datetime = [];
      this.currentStep = 0;
      this.fakeState = "";
      this.setCurrentStep(); // 根据审核数据设置当前进度步骤
    },
    // 获得员工某条请假单内容
    getFakeOneinfo() {
      let param = {
        companyId: this.UserInfo.companyId, // 公司id
        id: this.id // 请假单id
      };
      get_fakeinfo_one(param)
        .then(res => {
          //   for (let k in this.form) { this.$set(this.form, k, res[k]);  }
          this.form = Object.assign({}, res); // 赋默认值
          this.setCurrentStep(); // 根据审核数据设置当前进度步骤
          this.setFakeState();
        })
        .catch(err => {});
    },
    // 点击创建
    // 1 表单信息 + 公司id + 公司提供的审核关系 + 提交数据库
    handleCreate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let param = {
            ...this.form,
            companyId: this.UserInfo.companyId,
            relationship: this.UserInfo.relationship
          };
          console.log("这里", this.param);
          create_fakeinfo_one(param)
            .then(res => {
              this.init();
              this.$emit("refresh", { refresh: true, id: res.data.id });
              console.log("成功", res);
            })
            .catch(err => {
              console.log("失败", err);
            });
        } else {
          return false;
        }
      });
    },
    // 设置当前进度步骤
    setCurrentStep() {
      // 有表单数据后
      this.relativeNetwork = [];
      if (this.UserInfo.relationship) {
        this.UserInfo.relationship.forEach((item, index) => {
          if (index == 0) {
            this.relativeNetwork.push({
              ...item,
              desc: "发起人",
              icon: "el-icon-edit"
            });
          } else {
            // 在审核列表中存在且审核状态是0（待审核）
            if (this.form.Approvers && item.id in this.form.Approvers) {
              let status = this.form.Approvers[item.id].status;
              // 待审核 或者 已拒绝
              if (status === 0) {
                this.relativeNetwork.push({
                  ...item,
                  desc: "待审核",
                  icon: "el-icon-picture"
                });
                this.currentStep = index + 1;
              } else if (status === 2) {
                this.relativeNetwork.push({
                  ...item,
                  desc: "已拒绝",
                  icon: "el-icon-picture"
                });
                this.currentStep = index;
              } else if (status === 1) {
                this.relativeNetwork.push({
                  ...item,
                  desc: "已通过",
                  icon: "el-icon-picture"
                });
                this.currentStep = index;
              }
            } else {
              this.relativeNetwork.push({ ...item, icon: "el-icon-picture" });
            }
          }
        });
      }
    }
  }
};
</script>
<style scoped>
.item {
  margin-bottom: 20px;
}
.form_box {
  border: 1px solid #ccc;
  padding: 10px;
}
</style>